<template>
  <a-row class="container rkManage">
    <a-row class="title-item">
      设备申领情况
      <a-button v-if="false" type="primary" style="position: absolute; right: 100px" @click="goToRuku">新建入库信息</a-button>
    </a-row>
    <a-row class="border">
      <a-col :span="6" class="a" style="position: relative">
        <h3 class="h2">
          <template v-if="isSwap">物资分布</template>
          <template v-else>物资分类</template>
        </h3>
        <a-icon @click="onSwap" type="swap" style="
            position: absolute;
            right: 10px;
            top: 10px;
            font-size: 20px;
            cursor: pointer;
          "/>
        <a-row class="list-left">
          <a-tree v-if="dataLoading && isSwap" :replaceFields="replaceFields" :treeData="listDataOne" :show-line="false" :show-icon="false">
            <template slot="custom" slot-scope="item">
              <div @click="onCheck(item)" class="hidden1" style="width: 100%">
                {{ item.name }}
                <template v-if="item.number">({{ item.number }})</template>
              </div>
            </template>
          </a-tree>
          <a-tree v-if="dataLoading && !isSwap" :replaceFields="replaceFields" :treeData="listDataTwo" :show-line="false" :show-icon="false">
            <template slot="custom" slot-scope="item">
              <div @click="onCheck(item)" class="hidden1" style="width: 100%">
                {{ item.name }}
                <template v-if="item.number">({{ item.number }})</template>
              </div>
            </template>
          </a-tree>
        </a-row>
      </a-col>
      <a-col :span="12" class="right">
        <div class="c">
          <a-row class="h2">申领情况</a-row>
          <a-button type="danger" @click="deltGoods" size="small" style="margin-right: 12px" v-if="userData.stockDelect.includes($user.username)">删除</a-button>
<!--          <a-button class="exportbtn">-->
<!--            <a-icon type="cloud-download" />-->
<!--            导出数据-->
<!--          </a-button>-->
        </div>
        <a-table :row-selection="rowSelection" :rowKey="(record) => record.id" :columns="columns" :data-source="datas" :pagination="false" style="min-height: calc(100% - 90px)">
          <span slot="action" slot-scope="text, record">
            <!-- <a class="solvebtn" @click="showModal(record, index)">查看详情</a> -->
            <a class="solvebtn" @click="applyBtn(record, 1)">申请</a>
<!--            <a class="solvebtn" style="margin-left: 20px" @click="applyBtn(record, 2)">退回</a>-->
          </span>
        </a-table>
        <div class="page-box">
          <a-pagination :show-total="(total) => `共 ${total}条记录`" v-model="current" :total="total" :defaultPageSize="size" :item-render="itemRender" @change="pagechangeFn"/>
        </div>
        <a-modal v-model="isshow_apply" :title="`${titlename}信息`" @ok="applySave" @cancel="applyCancel" centered width="40%">
          <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }" layout="horizontal" :colon="false">
                <a-form-item :label="`${titlename}数量`">
                  <a-input-number id="inputNumber" :min="0" v-model="applyNumber"/>
                  {{ colProps }}
                </a-form-item>
                <a-form-item :label="`${titlename}说明`">
                  <a-textarea :placeholder="`请输入${titlename}说明`" :rows="4" v-model="applyCon"/>
                </a-form-item>
          </a-form>
        </a-modal>
      </a-col>
    </a-row>
  </a-row>
</template>

<script>
import moment from "moment";
import tree from "@/libs/tree";
export default {
  data() {
    return {
      userData,
      titlename: "",
      isSwap: true,
      listDataOne: [],
      listDataTwo: [],
      demoList: [],
      applyCon: "", //申请内容
      applyNumber: "", //申请数量
      isshow_apply: false,
      replaceFields: {
        children: "goodsAreaInfoPoList",
        title: "name",
        key: "id",
      },
      dataLoading: false,
      initdata: [],
      datas: [],
      columns: [
        {
          title: "序号",
          dataIndex: "id",
          align: "center",
          width: 100,
          customRender: (text, record, index) =>
            `${(this.current - 1) * this.size + index + 1}`,
        },
        {
          title: "区域",
          dataIndex: "areaName",
          align: "center",
          ellipsis: "true",
        },
        {
          title: "物资名称",
          dataIndex: "goodsTypeInfo.name",
          align: "center",
          ellipsis: "true",
        },
        {
          title: "物资型号",
          dataIndex: "goodsTypeInfo.version",
          align: "center",
          ellipsis: "true",
        },
        {
          title: "物资数量",
          dataIndex: "useableNumber",
          align: "center",
          width: 120,
        },
        {
          title: "待审核数量",
          dataIndex: "lockedNumber",
          align: "center",
          width: 140,
        },
        {
          title: "操作",
          dataIndex: "address",
          align: "center",
          width: 100,
          scopedSlots: { customRender: "action" },
        },
      ],
      current: 1,
      size: 10,
      total: 0,
      loading: false,
      activeKey: 0,
      treeList: [], //左侧树列表
      standbyProduct: [], //备品列表
      MachineSpare: "", //备机共计
      ProductSpare: "", //备品共计
      detailList: [],
      spareInfoDetails: [],
      userId: "",
      areaId:'',
      typeId:'',
      deltFrom:{
        selectedRows:[],
        selectedRowKeys:[],
      },

    };
  },
  computed: {
    colProps: function () {
      if (this.titlename != "退回") {
        if (this.applyNumber > this.demoList.useableNumber)
          return "你输入的数量超过库存数";
      }
    },
    rowSelection(){
      return{
        onChange:(selectedRowKeys, selectedRows)=>{
          this.deltFrom.selectedRowKeys = selectedRowKeys;
          this.deltFrom.selectedRows = selectedRows.map(v=>v.goodsId);
        },
        selectedRowKeys:this.deltFrom.selectedRowKeys
      }
    }
  },
  mounted() {
    this.searchType();
  },
  methods: {
    applySave() {
      console.log(this.demoList)
      if (this.titlename == "申领") {
        if (this.applyNumber > this.demoList.useableNumber) {
          return this.$message.info("你输入的数量超过库存数");
        }
        let data = {
          goodsId:this.demoList.goodsId,
          number: this.applyNumber,
          userId: this.$user.id,
          notes: this.applyCon,
        };
        this.$api.goodsApply(data).then((res) => {
          if(res.data.code === 0){
            this.$message.info(res.data.errorMessage);
            this.isshow_apply = false;
            this.applyNumber = "";
            this.applyCon = "";
            this.onCheck([],true);
          }else {
            this.$message.warning(res.data.errorMessage)
          }
        });
      } else {
        let data = {
          goodsId: this.demoList.goodsId,
          number: this.applyNumber,
          userId: this.$user.id,
          notes: this.applyCon,
          areaId: this.$user.deptId,
        };
        var _this=this;
        this.$api.backgoodsinfo(data).then((res) => {
            // for (let i = 0; i < this.datas.length; i++) {
            //     if(_this.datas[i].goodsId==_this.demoList.goodsId){
            //         _this.datas[i].useableNumber=Number(_this.datas[i].useableNumber)+Number(_this.applyNumber)
            //     }
            // }
            _this.searchType();
        });
      }

    },
    // 删除
    deltGoods(data){
      if(this.deltFrom.selectedRows.length===0)return this.$message.warning("请选择要删除的数据！")
      let then = this;
      this.$confirm({
        title: '是否确认删除?',
        onOk() {
          then.$api.goodsRemoveGoods({id:then.deltFrom.selectedRows}).then(res=>{
            if (res.data.code === 0){
              then.selectedRows = [];
              then.searchType();
              then.onCheck([],true);
              then.$message.info("删除成功！");
            }else {
              then.$message.error(res.data.errorMessage)
            }
          })
        },
        onCancel() {
          return;
        },
      });

    },
    // 删除完
    applyCancel() {
      this.isshow_apply = false;
      this.applyNumber = "";
      this.applyCon = "";
    },
    goToRuku() {
      this.$router.push({
        path: "ruku",
      });
    },
    // createIterator(items) {
    //     items.forEach((res) => {
    //         res.scopedSlots = {title: "custom"};
    //         if (res.goodsTypeNumberPoList && res.goodsTypeNumberPoList.length > 0) {
    //             return this.createIterator(res.goodsTypeNumberPoList);
    //         }
    //     });
    //     return items;
    // },
    searchType() {
      this.$api.getGoodsTypeTotal(this.$user.id).then((res) => {
        if (res.data.code == 0) {
          let data = res.data.data;
          this.listDataTwo = this.createIteratorOf(data);
          this.listDataOne = this.createIterator(data);
          this.dataLoading = true;
          console.log(this.listDataOne);
          console.log(this.listDataTwo);
        } else {
          this.$message.info(res.data.errorMessage);
        }
      });
    },
    createIteratorOf(data) {
      let list = [];
      data.goodsTypePoList.forEach((res) => {
        let areaId = [];
        let number = new Map();
        res.areaGoodsNumberPoList.forEach((item) => {
          areaId.push(item.areaId);
          number.set(item.areaId, item.number);
        });
        res.areaIdList = areaId;
        res.areaMap = number;
        list.push(res);
      });
      list.forEach((res) => {
        let sum = 0;
        tree.setConfig({
          children: "goodsAreaInfoPoList",
        });
        res.goodsAreaInfoPoList = [];
        let _map = new Map();
        let _list = [];
        res.areaIdList.forEach((item) => {
          let path = [];
          tree.treeFindPath(
            data.goodsAreaInfoPo.goodsAreaInfoPoList,
            (data) => {
              return item === data.id;
            },
            path
          );
          if (path.length != 0) {
            let _goodsAreaInfoPoList = {};

            if (_map.has(path[0].id)) {
              _goodsAreaInfoPoList = _map.get(path[0].id);
              _goodsAreaInfoPoList.goodsAreaInfoPoList.push({
                scopedSlots: { title: "custom" },
                id: path[1].id,
                areaId: path[1].id,
                name: path[1].name,
                typeId: res.typeId,
                isClick: true,
                number: res.areaMap.get(path[1].id),
              });
              sum += res.areaMap.get(path[1].id);
              _goodsAreaInfoPoList.number = sum;
            } else {
              _goodsAreaInfoPoList = {
                scopedSlots: { title: "custom" },
                id: path[0].id,
                areaId: path[0].id,
                name: path[0].name,
                number: res.areaMap.get(path[1].id),
                typeId: res.typeId,
                isClick: true,
                goodsAreaInfoPoList: [
                  {
                    scopedSlots: { title: "custom" },
                    id: path[1].id,
                    areaId: path[1].id,
                    name: path[1].name,
                    typeId: res.typeId,
                    isClick: true,
                    number: res.areaMap.get(path[1].id),
                  },
                ],
              };
              sum += res.areaMap.get(path[1].id);
            }

            _map.set(path[0].id, _goodsAreaInfoPoList);
            _list.push(_goodsAreaInfoPoList) ;
          }
        });
        let returnArray = [];
        for (let key of _map) {
          returnArray.push(key[1]);
        }
        res.goodsAreaInfoPoList=returnArray ;

        res.scopedSlots = { title: "custom" };
        res.number = sum;
      });
      return list;
    },
    createIterator(data) {
      let map = new Map();
      data.goodsTypeNumberPoList.forEach((item) => {
        item.isClick = true;
        item.scopedSlots = { title: "custom" };
        if (map.has(item.areaId)) {
          let _array = map.get(item.areaId);
          _array.push(item);
          map.set(item.areaId, _array);
        } else {
          let _array = [];
          _array.push(item);
          map.set(item.areaId, _array);
        }
      });
      let sum = function (items) {
        let sum = 0;
        items.forEach((res) => {
          sum += parseInt(res.number);
        });
        return sum;
      };
      let fun = function (items) {
        items.forEach((res) => {
          res.disabled = false;
          res.scopedSlots = { title: "custom" };
          if (res.goodsAreaInfoPoList && res.goodsAreaInfoPoList.length > 0) {
            return fun(res.goodsAreaInfoPoList);
          } else {
            if (map.has(res.id)) {
              res.number = sum(map.get(res.id));
              res.goodsAreaInfoPoList = map.get(res.id);
            }
          }
        });
        items.forEach((res) => {
          res.number = sum(res.goodsAreaInfoPoList);
        });
        return items;
      };
      return fun(data.goodsAreaInfoPo.goodsAreaInfoPoList);
    },

    onSwap() {
      this.isSwap = !this.isSwap;
    },

    onCheck(info,isPage=false) {
      this.deltFrom={
        selectedRows:[],
        selectedRowKeys:[]
      }
      if(!isPage){
        if(!info.areaId){
          info.areaId=info.id
        }
        this.areaId=info.areaId
        this.typeId=info.typeId
        this.current=1
      }
      this.$api.getAreaGoodsInfo({areaId: this.areaId,typeId: this.typeId,currentPage:this.current,pageSize:this.size}).then((res) => {
          this.datas = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 分页器
    itemRender(current, type, originalElement) {
      if (type === "prev") {
        return <a> 上一页 </a>;
      } else if (type === "next") {
        return <a> 下一页 </a>;
      }
      return originalElement;
    },
    pagechangeFn(page, pageSize) {
      console.log(page, pageSize);
      this.current = page;
      this.size = pageSize;
      this.onCheck([],true);
    },
    open(index) {
      this.activeKey = index;
    },
    applyBtn(item, index) {
      if (index == 1) {
        this.isshow_apply = true;
        this.demoList = item;
        this.titlename = "申领";
      } else {
        this.isshow_apply = true;
        this.demoList = item;
        this.titlename = "退回";
      }
    },
    handleOk(e) {
      //申请物资
      // console.log(e);
      this.isshow_apply = false;
      let data = {
        number: this.applyNumber,
        note: this.applyCon,
      };
    },
  },
};
</script>
<style scoped src = "../../../assets/style/pollution.css"></style>
<style scoped lang="scss">
.h2 {
  color: #000;
  line-height: 40px;
  margin-left: 30px;
}

.border {
  height: calc(100% - 60px);
  overflow-y: auto;
}

.list-left {
  height: calc(100% - 40px);
  overflow-y: auto !important;
  overflow-x: hidden;
}

.a {
  height: 100%;
  width: 24%;
  border: 1px solid #1890ff;
}

.title-item {
  /* border: 1px solid yellow; */
  height: 60px;
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.beijing {
  margin-left: 20px;
}

.wen {
  color: #9fb043;
}

.zi {
  color: #bebebe;
  text-align: center;
}

.right {
  border: 1px solid #1890ff;
  height: 100%;
  width: 76%;
  box-sizing: border-box;
}

.exportbtn {
  background-color: transparent;
  border: 0;
  color: #207064;
  margin-top: 10px;
}

.c {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

::v-deep .ant-tree {
  font-size: 16px;
}

.ant-form-item {
  margin-left: 20px;
}

/* 分页 */
.page-box {
  margin-top: 12px;
  float: right;
}

.totalclass {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  margin-right: 20px;
}

::v-deep.ant-form-item-control {
  width: 200px;
}


.container {
  height: 100%;
  width: 100%;
}
.solvebtn {
  color: #1890ff;
}
</style>
